# -*- coding: utf-8 -*-
import os
import sys
import shutil
import subprocess
import venv
import time

def rebuild_venv():
    print("开始重建虚拟环境...")
    
    # 虚拟环境路径
    venv_path = "venv"
    
    # 指定 Python 解释器路径（根据需要修改版本）
    python_version = "3.12"  # 指定想要的版本
    
    try:
        # 检查指定版本是否可用
        result = subprocess.run(
            ["py", f"-{python_version}", "-V"],
            capture_output=True,
            text=True
        )
        if result.returncode != 0:
            print(f"错误: 未找到 Python {python_version}，请先安装")
            sys.exit(1)
    except:
        print(f"错误: 未找到 Python {python_version}，请先安装")
        sys.exit(1)
    
    # 删除现有虚拟环境
    if os.path.exists(venv_path):
        print("删除现有虚拟环境...")
        try:
            # 先尝试删除 Scripts 目录下的可执行文件
            if sys.platform == "win32":
                scripts_dir = os.path.join(venv_path, "Scripts")
                if os.path.exists(scripts_dir):
                    for file in os.listdir(scripts_dir):
                        try:
                            file_path = os.path.join(scripts_dir, file)
                            if os.path.isfile(file_path):
                                os.chmod(file_path, 0o777)  # 修改权限
                                os.remove(file_path)
                        except Exception as e:
                            print(f"警告: 无法删除文件 {file}: {e}")
            
            # 等待一会儿
            time.sleep(1)
            
            # 删除整个虚拟环境
            shutil.rmtree(venv_path, ignore_errors=True)
            
            # 再等待一会儿
            time.sleep(1)
            
        except Exception as e:
            print(f"警告: 删除虚拟环境时出错: {e}")
            print("请确保已关闭所有 Python 程序，并手动删除 venv 目录后重试")
            sys.exit(1)
    
    # 使用指定版本创建虚拟环境
    print(f"使用 Python {python_version} 创建虚拟环境...")
    try:
        subprocess.check_call([
            "py",
            f"-{python_version}",
            "-m",
            "venv",
            venv_path
        ])
    except Exception as e:
        print(f"创建虚拟环境失败: {e}")
        sys.exit(1)
    
    # 获取python和pip路径
    if sys.platform == "win32":
        python_path = os.path.join(venv_path, "Scripts", "python.exe")
        pip_path = os.path.join(venv_path, "Scripts", "pip.exe")
    else:
        python_path = os.path.join(venv_path, "bin", "python")
        pip_path = os.path.join(venv_path, "bin", "pip")
    
    try:
        # 升级pip
        print("升级pip...")
        subprocess.check_call([
            python_path, 
            "-m", 
            "pip", 
            "install", 
            "--upgrade", 
            "pip",
            "-i",
            "https://pypi.tuna.tsinghua.edu.cn/simple",
            "--trusted-host",
            "pypi.tuna.tsinghua.edu.cn"
        ])
        
        # 安装依赖
        print("安装依赖...")
        subprocess.check_call([
            pip_path,
            "install",
            "-r",
            "requirements.txt",
            "-i",
            "https://pypi.tuna.tsinghua.edu.cn/simple",
            "--trusted-host",
            "pypi.tuna.tsinghua.edu.cn"
        ])
        
        print("虚拟环境重建完成！")
        
    except subprocess.CalledProcessError as e:
        print(f"安装依赖失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    # 确保当前没有激活的虚拟环境
    if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
        print("错误: 请先退出当前的虚拟环境 (deactivate)")
        sys.exit(1)
    
    rebuild_venv() 